package com.shortLinked.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shortLinked.admin.common.biz.user.UserContext;
import com.shortLinked.admin.common.constant.RedisCacheConstant;
import com.shortLinked.admin.common.convention.exception.ClientException;
import com.shortLinked.admin.common.enums.UserErrorCode;
import com.shortLinked.admin.dao.entity.UserDO;
import com.shortLinked.admin.dao.mapper.UserMapper;
import com.shortLinked.admin.dto.req.UserLoginReqDTO;
import com.shortLinked.admin.dto.req.UserRegisterReqDTO;
import com.shortLinked.admin.dto.req.UserUpdateReqDTO;
import com.shortLinked.admin.dto.resp.UserLoginRespDTO;
import com.shortLinked.admin.dto.resp.UserRespDTO;
import com.shortLinked.admin.service.GroupService;
import com.shortLinked.admin.service.UserService;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static com.shortLinked.admin.common.constant.RedisCacheConstant.USER_LOGIN_KEY;

/**
 * 用户接口实现层
 *
 * @since 2024-05-19
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService {

    private final RBloomFilter<String> userRegisterCachePenetrationBloomFilter;   // 用户注册缓存穿透布隆过滤器
    private final RedissonClient redissonClient; // 分布式锁

    private final GroupService groupService;

    private final StringRedisTemplate stringRedisTemplate;

    @Override
    public UserRespDTO getUserByUsername(String username) {
        LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class)
                .eq(UserDO::getUsername, username);
        UserDO user = baseMapper.selectOne(queryWrapper); // 获取到用户的信息
        if (user == null) {
            throw new ClientException(UserErrorCode.USER_NULL); // 抛出客户端异常，通过全局异常拦截器进行拦截
        }
        UserRespDTO result = new UserRespDTO(); // 返回用户信息
        BeanUtils.copyProperties(user, result); // 进行一个拷贝
        return result;
    }

    @Override
    public Boolean hasUsername(String username) {
        return !userRegisterCachePenetrationBloomFilter.contains(username);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void registerUser(UserRegisterReqDTO requestParam) {
        if (!hasUsername(requestParam.getUsername())) {
            throw new ClientException(UserErrorCode.USER_NAME_EXIST);
        }
        // 短链接新增用户分布式锁
        RLock lock = redissonClient.getLock(RedisCacheConstant.LOCK_USER_REGISTER_KEY + requestParam.getUsername());
        if (!lock.tryLock()) {
            throw new ClientException(UserErrorCode.USER_NAME_EXIST);
        }
        try {
            int insert = baseMapper.insert(BeanUtil.toBean(requestParam, UserDO.class));
            if (insert < 1) {
                throw new ClientException(UserErrorCode.USER_INSERT_ERROR);
            }
            // 新创建用户为默认分组
            groupService.saveGroup(requestParam.getUsername(), "默认分组");
            // 布隆过滤器新增用户数据
            userRegisterCachePenetrationBloomFilter.add(requestParam.getUsername());
        } catch (DuplicateKeyException ex) {
            // 用户记录已存在
            throw new ClientException(UserErrorCode.USER_EXIST);
        } finally {
            lock.unlock();
        }
    }


    @Override
    public void updateUser(UserUpdateReqDTO requestParam) {
        if (!Objects.equals(requestParam.getUsername(), UserContext.getUsername())) {
            throw new ClientException("当前登录用户修改请求异常");
        }
        LambdaUpdateWrapper<UserDO> updateWrapper = Wrappers.lambdaUpdate(UserDO.class)
                .eq(UserDO::getUsername, requestParam.getUsername());
        baseMapper.update(BeanUtil.toBean(requestParam, UserDO.class), updateWrapper);
    }

    @Override
    public UserLoginRespDTO login(UserLoginReqDTO requestParam) {
        // 先验证用户名 / 密码是否存在
        LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class)
                .eq(UserDO::getUsername, requestParam.getUsername())
                .eq(UserDO::getPassword, requestParam.getPassword())
                // 0 -> 没有被注销的用户
                .eq(UserDO::getDelFlag, 0);
        UserDO tUser = baseMapper.selectOne(queryWrapper);
        if (tUser == null) {
            throw new ClientException(UserErrorCode.USER_NULL);
        }
        // 用户登录之后 - 直接返回 token
        // 获取所有的键值 - key
        Map<Object, Object> hasLoginMap = stringRedisTemplate.opsForHash().entries(USER_LOGIN_KEY + requestParam.getUsername());
        if (CollUtil.isNotEmpty(hasLoginMap)) {
            // 刷新一下 token 有效期
            stringRedisTemplate.expire(USER_LOGIN_KEY + requestParam.getUsername(), 30L, TimeUnit.MINUTES);
            String token = hasLoginMap.keySet().stream()
                    .findFirst()
                    .map(Object::toString)
                    .orElseThrow(() -> new ClientException("用户登录错误"));
            return new UserLoginRespDTO(token);
        }
        /**
         * 使用hash结构存储
         * key: login_ + 'username'
         * value
         * 小key   token（uuid），json（tUser）
         */
        String uuid = UUID.randomUUID().toString();
        stringRedisTemplate.opsForHash().put(USER_LOGIN_KEY + requestParam.getUsername(), uuid, JSON.toJSONString(tUser));
        stringRedisTemplate.expire(USER_LOGIN_KEY + requestParam.getUsername(), 30L, TimeUnit.MINUTES);
        return new UserLoginRespDTO(uuid);
    }

    @Override
    public Boolean checkLogin(String username, String token) {
        return stringRedisTemplate.opsForHash().get(USER_LOGIN_KEY + username, token) != null;
    }

    @Override
    public void logout(String username, String token) {
        // 检查用户是否登录
        if (checkLogin(username, token)) {
            stringRedisTemplate.delete(USER_LOGIN_KEY + username);
            return;
        }
        throw new ClientException("token不存在或者用户未登录");
    }
}
